/*
 *
 * Created on: 25.06.2012
 *
 * main.cpp
 * This file is part of KOBUS
 * 
 * Copyright (C) 2012 - Ivan Penkin, MIPT
 * grek.penkin@gmail.com
 *
 * KOBUS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * KOBUS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with KOBUS; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, 
 * Boston, MA  02110-1301  USA
 *  
 */

#include <QSettings>
#include <QtNetwork>

#include <KobusCommon.h>

#include <DHLogAnalyzer.h>
#include <DHConfig.h>


using namespace kobus;
using namespace kobus::dhcp;


int main (int argc, char** argv ) {

  QDaemonApplication app(argc, argv);
  QTextStream err(stderr);

  QString logName(argv[0]);
  Log log(
        logName.split(QDir::separator(), QString::SkipEmptyParts).back(),
        Log::LogPid, Log::LogDaemon
      );

  DHConfig cfg(_DHCP_ANALYSER_CONF, &app);
  try {
    cfg.read();
    if (!cfg.check()) {
      throw Exception(Exception::NO_ERRNO, "Wrong config file.");
    }
  } catch (Exception e) {
    err << "Unable to read .conf file." << endl
        << "Please, read log for more information." << endl;
    return EXIT_FAILURE;
  };

  DHLogAnalyzer analyzer(&app);

  class TmpException {};

  try {
    if (!cfg.contains(DHConfig::Keys::daemon::user)) {
      throw TmpException();
    };

    if (!app.setUserName(cfg.getString(DHConfig::Keys::daemon::user))) {
      throw TmpException();
    }
  } catch (...) {
    log.warning("Unable to set working user-name.");
  };

  try {
    if (!cfg.contains(DHConfig::Keys::daemon::group)) {
      throw TmpException();
    }

    if (!app.setGroupName(cfg.getString(DHConfig::Keys::daemon::group))) {
      throw TmpException();
      qDebug() << "!app.setUserName";
    }
  } catch (...) {
    log.warning("Unable to set working group-name.");
  }

  // TODO: fix singleShot timeout
  QTimer::singleShot(500,  &analyzer, SLOT( start() ));

  return app.exec();
}


